package com.totoro.tygeneratedragonblock.executor.command.impl;

import com.totoro.tygeneratedragonblock.TyGenerateDragonBlock;
import com.totoro.tygeneratedragonblock.constants.StaticSystemVarConst;
import com.totoro.tygeneratedragonblock.executor.command.MainCommandExecutor;
import com.totoro.tygeneratedragonblock.pojo.SpawnPoint;
import com.totoro.tygeneratedragonblock.utils.ColorUtil;
import com.totoro.tygeneratedragonblock.utils.StrUtil;
import org.bukkit.Location;
import org.bukkit.block.BlockFace;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.plugin.Plugin;

/**
 * @author Totoro
 * @version 0.1.0
 * @date 2025/8/10 - 18:45
 * @description
 **/
public class SpawnCommandExecutor implements MainCommandExecutor {
    @Override
    public void execute(TyGenerateDragonBlock plugin, CommandSender sender, String[] args) {
        if(!judgePermission(plugin, sender, null)) {
            return;
        }
        if(!(sender instanceof Player)) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c该指令不能由控制台执行!"));
            return;
        }
        Player player = (Player) sender;
        if(args.length != 4) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c用法: /tgdb spawn <方块ID> <刷新点ID> <冷却时间>"));
            return;
        }
        // 获取方块ID
        String blockId = args[1];
        String spawnId = args[2];
        // 刷新时间
        boolean nonNegativeNumber = StrUtil.isNonNegativeNumber(args[3]);
        if(!nonNegativeNumber) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c刷新时间必须是正数！"));
            return;
        }
        double cooldown = Double.parseDouble(args[3]);
        // 检查方块Id是否存在配置中
        if (! plugin.getBlocksManager().getBlockDefinitions().containsKey(blockId)) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c未在方块配置中找到该ID的方块！"));
            return;
        }

        // 判断刷新点是否存在
        if (plugin.getSpawnersManager().getSpawnPoints().containsKey(spawnId)) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c该刷新点已存在！"));
            return;
        }

        // 获取位置（玩家脚下的方块）
        Location location = player.getLocation().getBlock().getRelative(BlockFace.DOWN).getLocation();

        // 创建新刷新点
        SpawnPoint newSpawn = new SpawnPoint(spawnId, blockId, cooldown, location);
        // 保存到配置
        Boolean isSave = plugin.getSpawnersManager().saveSpawnersFile(newSpawn);
        if(!isSave) {
            sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + ColorUtil.color("&c保存刷新点失败！"));
            return;
        }
        sender.sendMessage(plugin.getConfigManager().getConfig().getPrefix() + String.format(ColorUtil.color("&6成功创建方块 [&c%s&6] 的刷新点 [&c%s&6]！"), blockId, spawnId));
    }
}
